package com.zhangwei.exception;

import com.zhangwei.pojo.bean.ResultVO;
import com.zhangwei.utils.ResultVoUtil;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 通过使用@ControllerAdvice定义统一的异常处理类，而不是在每个Controller中逐个定义
@ControllerAdvice
//拦截异常，全局异常统一处理只能针对于Controller层的异常，意思是只能捕获到Controller层的异常，在service层或者其他层面的异常都不能捕获。
public class MyExceptionHandler {

    public static final String ERROR_VIEW = "error";

    // @ExceptionHandler用来定义函数针对的异常类型，最后将Exception对象和请求URL映射到error.html中
    @ExceptionHandler(value = Exception.class)
//    @ResponseBody  //针对json数据
    public ModelAndView errorHtmlHandler(HttpServletRequest request, HttpServletResponse response,  //注意是HttpServletRequest
            Exception e) throws Exception {
        // 全局捕获Exception.class异常, 跳转到error.ftl模板
//        e.printStackTrace();
        ModelAndView mav = new ModelAndView();
        mav.setViewName("exception");  //设置模板的路径及名称
        mav.addObject("exception", e);
        mav.addObject("url", request.getRequestURI());   //HttpRequest的request.getURI()会报错
//        System.out.println("request.getURI："+request.getURI());

        return mav;
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ResultVO errorJsonHandler(HttpRequest request, HttpServletResponse response,
                                     Exception e) throws Exception {



        return ResultVoUtil.error(1,"json err");
    }

//    @ExceptionHandler(value = Exception.class)
//    public Object errorHandler(HttpServletRequest request,
//                               HttpServletResponse response, Exception e) throws Exception {
//        e.printStackTrace();
//        if (isAjax(request)) {
//            return ResultVoUtil.error(1,"is ajax err");
//        } else {
//            ModelAndView mav = new ModelAndView();
//            mav.addObject("exception", e);
//            mav.addObject("url", request.getRequestURL());
//            mav.setViewName(ERROR_VIEW);
//            return mav;
//        }
//    }
//
//    // 判断是否是ajax请求
//    private static boolean isAjax(HttpServletRequest httpRequest){
//        return  (httpRequest.getHeader("X-Requested-With") != null
//                && "XMLHttpRequest"
//                .equals( httpRequest.getHeader("X-Requested-With").toString()) );
//    }

}

